package com.xiaocz.hblsubstitutedriving.activities.fragment;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.AppCompatImageView;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.umeng.analytics.MobclickAgent;
import com.xiaocz.common.widgets.load.LoadFactory;
import com.xiaocz.common.widgets.load.core.LoadManager;
import com.xiaocz.common.widgets.load.view.AbsView;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.base.BaseFragment;
import com.xiaocz.hblsubstitutedriving.widget.ErrorView;
import com.xiaocz.hblsubstitutedriving.widget.LoadingView;

import butterknife.BindView;
import butterknife.OnClick;

public class HomeFragment extends BaseFragment {

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.web_view)
    public WebView mWebView;

    /**
     * DATA
     */
    private LoadManager mLoadManager;
    private static String normUrl;

    @Override
    protected void initWidgets(View rootView) {
        super.initWidgets(rootView);
        mLoadManager = LoadFactory.getInstance().register(mWebView, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManager.showStateView(LoadingView.class);
                loadWeb(normUrl);
            }
        });
        mWebView.setOnKeyListener(new View.OnKeyListener() {

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
                    getActivity().runOnUiThread(new Runnable() {
                        public void run() {
                            mWebView.goBack();
                        }
                    });
                    return true;
                }
                return false;
            }
        });
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.finishRefresh();
                loadWeb(normUrl);
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        loadWeb(normUrl);
    }

    // Fragment页面onResume函数重载
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TAG); //统计页面("MainScreen"为页面名称，可自定义)

    }

    // Fragment页面onResume函数重载
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);
    }

    private boolean errorState;

    /**
     * loadWeb 加载页面
     *
     * @param url 网址
     */
    private void loadWeb(String url) {
        try {
            errorState = false;
            WebSettings webSettings = mWebView.getSettings();
            webSettings.setJavaScriptEnabled(true);// 设置支持javascript
            mWebView.setWebChromeClient(new WebChromeClient() {

                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    super.onProgressChanged(view, newProgress);
                    try {
                        if (newProgress == 100) {
                            if (!errorState) {
                                mLoadManager.showSuccessView();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onReceivedTitle(WebView view, String titleValue) {
                    super.onReceivedTitle(view, titleValue);
                    if (titleValue.equals("lic")) {
                        errorState = true;
                        mLoadManager.showStateView(ErrorView.class);
                    }
                }
            });

            mWebView.setWebViewClient(new WebViewClient() {

                public void onReceivedError(WebView view, int errorCode,
                                            String description, String failingUrl) {
                    super.onReceivedError(view, errorCode, description, failingUrl);
                    mLoadManager.showStateView(ErrorView.class);
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (url.contains("tel:")) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_CALL);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                        return true;
                    } else {
                        return super.shouldOverrideUrlLoading(view, url);
                    }
                }
            });
            mWebView.loadUrl(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static HomeFragment newInstance(String url) {
        normUrl = url;
        HomeFragment homeFragment = new HomeFragment();
        return homeFragment;
    }

    @Override
    public void onDestroy() {
        if (mWebView != null) {
            mWebView.destroy();
            mWebView.destroyDrawingCache();
        }
        mWebView = null;
        super.onDestroy();
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.fragment_home;
    }

    public interface FragmentOnclick {
        void onRightOnClick(final String toastStr);
    }
}
